package com.ray.ray.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;



import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.TelephonyNew;
import android.util.Log;

public class MMSUtil {
	public static Uri insert(Context context, String[] to, String subject,String filePath,String text)
	{
	    try
	    {
	    	Bitmap imageBitmap = BitmapFactory.decodeFile(filePath);
	    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    	imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
	        byte[] imageBytes = baos.toByteArray();
	        Uri destUri = Uri.parse("content://mms/sent");
	        // Get thread id
	        Set<String> recipients = new HashSet<String>();
	        recipients.addAll(Arrays.asList(to));
	        long thread_id = TelephonyNew.Threads.getOrCreateThreadId(context, recipients);
	        // Create a new message entry
	        ContentValues mmsValues = new ContentValues();
	        mmsValues.put("thread_id", thread_id);
	        mmsValues.put("date", System.currentTimeMillis()/1000);
	        mmsValues.put("ct_t", "application/vnd.wap.multipart.related");
	        mmsValues.put("read", "1");
	        mmsValues.put("sub", subject);
	        
	        mmsValues.put("m_id", "1");
	        mmsValues.put("m_cls", "personal");
	        mmsValues.put("m_type", "132");
	        mmsValues.put("v", "16");
	        mmsValues.put("tr_id", "2830000067439141109105048001");
	        mmsValues.put("d_rpt", "129");
	        mmsValues.put("seen", "1");
	        mmsValues.put("sub_id", "1");
	        mmsValues.put("network_type", "1");
	        
	        
	     // Insert message
	        Uri res = context.getContentResolver().insert(destUri, mmsValues);
	       
	        // Create part
	        long dummyId = System.currentTimeMillis();
	        String messageId = res.getLastPathSegment().trim();
	        long id1 = System.currentTimeMillis();
	        createStart(context, id1,"",messageId,text);
	        ContentValues updateValues2 = new ContentValues();
	        updateValues2.put("mid", messageId);
	        Uri updateUri2 = Uri.parse("content://mms/" + id1 + "/part");
	        int mmsPartRows3 = context.getContentResolver().update(updateUri2, updateValues2, null, null);
	        createPart(context, dummyId, imageBytes);
	        if(!(text == null || "".equals(text))) {
	        	 long dummyId1 = System.currentTimeMillis();
	        	createText(context, dummyId1, text);
	        	 // Update part
		        ContentValues updateValues1 = new ContentValues();
		        updateValues1.put("mid", messageId);
		        updateValues1.put("chset", 106);
		        updateValues1.put("fn", "text_0.txt");
		        updateValues1.put("cid", "<text_0.txt>");
		        updateValues1.put("cl", "text_0.txt");
		        Uri updateUri1 = Uri.parse("content://mms/" + dummyId1 + "/part");
		        int mmsPartRows1 = context.getContentResolver().update(updateUri1, updateValues1, null, null);
	        }
	       

	        // Update part
	        ContentValues updateValues = new ContentValues();
	        updateValues.put("mid", messageId);
	        updateValues.put("ct", "image/jpeg");
	        updateValues.put("name", "IMG_7572.jpg");
	        updateValues.put("cd", "attachment");
	        updateValues.put("cid", "<0>");
	        updateValues.put("cl", "IMG_7572.jpg");
	        updateValues.put("_data", filePath);
	        
	        
	        Uri updateUri = Uri.parse("content://mms/" + dummyId + "/part");
	        int mmsPartRows = context.getContentResolver().update(updateUri, updateValues, null, null);
	        // Create addresses
	        for (String addr : to)
	        {
	            ContentValues addrValues = new ContentValues();
	            addrValues.put("address", addr);
	            addrValues.put("charset", "106");
	            addrValues.put("type", 151); // TO
	            Uri addrUri = Uri.parse("content://mms/"+ messageId +"/addr");
	            Uri mmsAddrUri = context.getContentResolver().insert(addrUri, addrValues);
	        }
	        res = Uri.parse(destUri + "/" + messageId);
	        return res;
	    }
	    catch (Exception e)
	    {
	        e.printStackTrace();
	    }

	    return null;
	}

	private static Uri createStart(Context context,long id,String file,String mid,String text){
		ContentValues mmsPartValue = new ContentValues();
	    mmsPartValue.put("seq", -1);
	    mmsPartValue.put("ct", "application/smil");
	    mmsPartValue.put("cid", "<0.smil>");
	    StringBuffer sb = new StringBuffer();
	    sb.append("<smil>");
	    sb.append("<head>");
	    sb.append("<layout>");
	    sb.append("<root-layout/>");
	    sb.append("<region id=\"Text\" top=\"70%\" left=\"0%\" height=\"30%\" width=\"100%\" fit=\"scroll\"/>");
	    sb.append("<region id=\"Image\" top=\"0%\" left=\"0%\" height=\"70%\" width=\"100%\" fit=\"meet\"/>");
	    sb.append("</layout>");
	    sb.append("</head>");
	    sb.append("<body>");
	    sb.append("<par dur=\"10s\">");
	    if(!(null == text || "".equals(text))) {
	    	sb.append("<text src=\"text_0.txt\" region=\"Text\"/>");
	    }
	    sb.append("<img src=\"IMG_7572.jpg\" region=\"Image\"/>");
	    sb.append("</par>");
	    sb.append("</body>");
	    sb.append("</smil>");
	    mmsPartValue.put("text", sb.toString());
	    Uri partUri = Uri.parse("content://mms/" + id + "/part");
	    Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
	    return res;
	}
	
	private static Uri createPart(Context context, long id, byte[] imageBytes) throws Exception
	{
	    ContentValues mmsPartValue = new ContentValues();
	    mmsPartValue.put("ct", "image/png");
	    Uri partUri = Uri.parse("content://mms/" + id + "/part");
	    Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
//	    Log.e(">>>>>>>", "Part uri is " + res.toString());
//
//	    // Add data to part
	    OutputStream os = context.getContentResolver().openOutputStream(res);
	    ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
	    byte[] buffer = new byte[256];
	    for (int len=0; (len=is.read(buffer)) != -1;)
	    {
	        os.write(buffer, 0, len);
	    }
	    os.close();
	    is.close();

	    return res;
	}
	private static Uri createText(Context context, long id, String text) throws Exception
	{
		ContentValues mmsPartValue = new ContentValues();
		mmsPartValue.put("text", text);
		mmsPartValue.put("ct", "text/plain");
		Uri partUri = Uri.parse("content://mms/" + id + "/part");
		Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
		return res;
	}
	
}
